<template>
    <nav>
        <span style="color:rgb(150, 150, 150)">当前位置 :</span><span @click="goToActivity()" >志愿项目</span>
        <i style="margin-left: 10px;" class="iconfont icon-dayuhao"></i>
        <span >项目详情</span>
    </nav>
  <div class="content">
    <el-row :gutter="10">
        <el-col :span="16" :xs="24">
            <el-card  >
                <template #header>
              <div class="card-header">
                <span>项目详情</span>
              </div>
            </template>
            <el-descriptions
            :title="activityInfo.title"
            direction="vertical"
            border
            style="margin-top:0px;"
        >
    <el-descriptions-item
        :rowspan="2"
        :width="140"
        align="center"
        >
      <el-image
        style="max-width: 150px; max-height: 150px; width: auto; height: auto;"

        :src="`${proxy.globalInfo.imageUrl}${activityInfo.activityId}?${timestamp}`"
      />
    </el-descriptions-item>
    <el-descriptions-item label="项目地点">{{activityInfo.location }}</el-descriptions-item>
    <el-descriptions-item label="发布日期">{{activityInfo.lastUpdateTime }}</el-descriptions-item>
    <el-descriptions-item label="项目日期">{{activityInfo.startTime }}~{{activityInfo.endTime }}</el-descriptions-item>

    <el-descriptions-item label="状态">
      <el-tag size="large" v-if="activityInfo.status==1"> 待启动 </el-tag>
      <el-tag size="large" v-if="activityInfo.status==2"> 运行中 </el-tag>
      <el-tag size="large" v-if="activityInfo.status==3"> 已结束 </el-tag>
    </el-descriptions-item>
    <el-descriptions-item  label="项目编号">
        {{activityInfo.activityId}}
    </el-descriptions-item>
    <el-descriptions-item  label="计划招募">
        {{activityInfo.maxParticipants}}
    </el-descriptions-item>
    <el-descriptions-item  label="已招募">
        {{activityInfo.joinMember}}
    </el-descriptions-item>
    </el-descriptions>

    <!---底部菜单--->
        <div class="bottom" style="margin-top: 20px;">
            <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
                <el-tab-pane label="项目详情" name="activityDesc">
                    <p style="font-size: 16px;">
                        {{activityInfo.description}}
                    </p>
                    <div class="nodata"  v-if="activityInfo.desciption==null||activityInfo.desciption==''">
                        暂无数据
                    </div>
                </el-tab-pane>
                <el-tab-pane label="报名信息" name="joinmemberInfo">
                    <div class="nodata" v-if="tableData.length===0">
                        暂无数据
                    </div>
                    <Table
                      ref="tableInfoRef"
                      :columns="columns"
                      :fetch="loadJoinMemberList"
                      :dataSource="tableData"
                      :options="tableOptions"
                      :extHeight="tableOptions.extHeight"
                     >
                     </Table>
                </el-tab-pane>

                <el-tab-pane label="评论列表" name="commentInfo">
                    <div class="nodata" v-if="commentInfoList.length===0">
                        暂无数据
                    </div>
                    <div style="overflow-y: auto;">
                      <div v-for="(item,i) in commentInfoList" :key="i" class="author-title reply-father">
                                <el-avatar  :size="40" >
                                    <Avatar
                                        :userId="item.userId"
                                        :timestamp="timestamp"
                                        :width="46"
                                      ></Avatar>
                                  </el-avatar>

                                <div class="author-info">
                                  <span class="author-name">{{item.name}}</span>
                                  <span class="author-time">{{item.createTime}}</span>
                                </div>
                                <div class="icon-btn">
                                  <span >对本次活动评分<i class="iconfont el-icon-s-comment icon-pingfen"></i>{{item.rating==null?"暂无评分":item.rating*20}}</span>
                                </div>
                                <div class="talk-box">
                                  <p>
                                      <span class="reply" v-html="item.comment"></span>
                                  </p>
                                </div>
                                </div>
                                <div >
                                <div v-clickoutside="hideReplyBtn" @click="inputFocus" class="my-reply">
                                  <div style="margin-left: 20px;">
                                      <div class="tip">用户评分</div>
                                      <el-rate
                                      v-model="rating4User"
                                      :texts="['20分', '40分', '60分', '80分', '100分']"
                                      show-text
                                      />
                                    </div>
                                      <div class="reply-info" >
                                          <div
                                          tabindex="0"
                                          contenteditable="true"
                                          id="replyInput"
                                          spellcheck="false"
                                          placeholder="输入评论..."
                                          class="reply-input"
                                          @focus="showReplyBtn"
                                          @input="onDivInput($event)"
                                          >
                                          </div>
                                      </div>
                                      <div class="reply-btn-box" v-show="btnShow">
                                      <el-button class="reply-btn" size="medium" @click="sendComment" type="primary">发表评论</el-button>
                                      </div>
                                  </div>
                                </div>
                                <div style="margin-top:10px">
                                    <el-pagination
                                    style="display: flex"
                                    v-model:current-page="tableData.pageNo"
                                    v-model:page-size="tableData.pageSize"
                                    :page-sizes="[15, 30, 35,50 ]"
                                    size="large"
                                    :pager-count="7"
                                    :disabled="disabled"
                                    :background="background"
                                    layout="total, sizes, prev, pager, next, jumper"
                                    :total="tableData.totalCount"
                                    @size-change="handleSizeChange"
                                    @current-change="handleCurrentChange"
                                    />
                                    </div>
                                   </div>
                                    </el-tab-pane>
                                            </el-tabs>
                                        </div>
                                        </el-card>
                                        </el-col>
                                        <el-col :span="8" :xs="24">
                                            <el-card>
                                                <template #header>
                                              <div class="card-header">
                                                <span>负责人信息</span>
                                              </div>
                                            </template>
                                            <el-descriptions
                                                direction="column"
                                                :column="1"
                                                :size="size"
                                                border
                                            >
              <el-descriptions-item label="姓名">{{activityInfo.createUserName}}</el-descriptions-item>
              <el-descriptions-item label="联系方式">{{activityInfo.email}}</el-descriptions-item>
              </el-descriptions>
            </el-card>
            <el-card style="background-color: aliceblue;margin-top: 10px;border-radius: 20px;">
                <el-button v-if="!isApply" @click="joinActivity" style="width: 60%;margin-left: 20%;background-color: rgb(29, 32, 136); height: 40px;border-radius: 20px; color: whitesmoke;" >我要报名</el-button>
                <el-button v-if="isApply" @click="showApplyDetail" style="width: 60%;margin-left: 20%;background-color: rgb(145, 220, 90); height: 40px;border-radius: 20px; color: whitesmoke;" >查看详情</el-button>

            </el-card>
        </el-col>
    </el-row>


  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, nextTick, onMounted } from "vue"
const { proxy } = getCurrentInstance();
import { useRoute,useRouter } from "vue-router";
import Avatar from "@/components/Avatar.vue";
const router = useRouter();
const route = useRoute();

const api={
    loadActivityDetail:"/account/loadActivityDetail",
    saveApply:"/apply/saveApply",
    saveRatingInfo:"/rating/saveRatingInfo",
    getRatingInfo:"/rating/getRatingInfo",
    loadJoinMemberList:"/apply/loadJoinMemberList",
}

const activeName = ref('activityDesc')

const activityId=ref();


// 获取当前页面的 活动id

// 跳转至主页
const goToActivity=()=>{
    router.push("/site/project");
}

const joinActivity= async()=>{
    if(activityInfo.value.status===3){
        proxy.Message.error("活动已经结束,无法报名");
    }
    if(activityInfo.value.joinMember>=activityInfo.value.maxParticipants){
        proxy.Message.error("活动人数已满，无法报名");
    }
    // 发起添加申请的请求
    let result = await proxy.Request({
       url:api.saveApply,
       params:{
        activityId:activityId.value,
       }
    })
    if(!result){
      return;
    }
    if(result.data===0){
        proxy.Message.success("报名成功，可在个人报名申请记录中查看");
    }else{
        proxy.Message.success("报名申请提交成功，可在个人报名申请记录中查看");
    }
    loadDataListById();
}

const showApplyDetail=()=>{
    router.push(`/user/applyInfo`);
}


// 获取页面参数
onMounted(()=>{
    activityId.value=route.query.activityId;
    loadDataListById();
    initCommentData();
    loadJoinMemberList();
})



const  isApply=ref(0);
// 活动详情
const activityInfo=ref({
     id:"1312313212321",
     title:"“青年智慧小青苗成长驿站”志愿服务活动第01期",
     status:1,
     desciption:"项目名称：“青年智慧小青苗成长驿站”志愿服务活动第01期 项目介绍：青年智慧小青苗成长驿站是一个专注于儿童青少年成长与发展的平台，致力于通过提供多样化的教育资源和活动，促进青少年的全面发展。 驿站地点：东营市广饶县青年智慧小青苗成长驿站（广饶县康居花园内） 驿站性质：公益性质（免费） 驿站工作时间：每周六、周天、节假日 活动日期：2024年11月23日-12月31日 活动时间：上午：07:30-12:00 下午13:00-17:30 项目负责人：冯瑞康 联系电话：19854628312 活动负责人：徐天一 联系电话：13546028680",
     startTime:"2024-11-22 ",
    endTime:"2024-12-31",
    lastUpdateTime:"2024-11-22",
    location:"	东营市广饶县青年智慧小青苗成长驿站",
    maxParticipants:20,
    joinMemberCount:10,
    createdBy:"张大致",
    email:"19814982081@139.com",
    imgSrc:"/src/assets/img/pic1.png",

    })

const loadDataListById = async () => {
  let result = await proxy.Request({
    url: api.loadActivityDetail,
    params: {
        activityId:activityId.value,
    },
  });
  if (!result) {
    return;
  }
  Object.assign(activityInfo.value, result.data.activityInfo);
  isApply.value=result.data.isApply;
};



//处理tab 切换
const handleClick=(tab, event)=>{

  switch (tab.props.name) {
    case 'activityDesc':
      console.log('activityDesc tab was clicked');
      break;

    case 'joinmemberInfo':
      loadJoinMemberList();
      break;

    case 'commentInfo':
      // commentInfo Tab时执行的逻辑
      initCommentData();
      break;

    default:
      // 如果是未知的Tab，则可以提供一个默认的行为或者报错
      console.warn('未知tab 点击:', tab);
  }
}



const loading = ref(false);

const rating4User=ref("");

const commentInfoList = ref([
  {
    userId:"",
    name: 'Lana Del Rey',
    content: '我发布一张新专辑Norman Fucking Rockwell,大家快来听啊',
    createTime: '2019年9月16日 18:43',
    rating: 2,
    inputShow: false,
}]);


const btnShow = ref(false);
const index = ref(0);
const replyComment = ref('');
const myName = ref('Lana Del Rey');
const myHeader = ref('https://ae01.alicdn.com/kf/Hd60a3f7c06fd47ae85624badd32ce54dv.jpg');
const to = ref('');
const toId = ref(-1);

const inputFocus = () => {
  const replyInput = document.getElementById('replyInput');
  replyInput.style.padding = "8px 8px";
  replyInput.style.border = "2px solid blue";
  replyInput.focus();
};

const showReplyBtn = () => {
  btnShow.value = true;
};

const hideReplyBtn = () => {
  btnShow.value = false;
  const replyInput = document.getElementById('replyInput');
  replyInput.style.padding = "10px";
  replyInput.style.border = "none";
};

const showReplyInput = (i, name, id) => {
  comments.value[index.value].inputShow = false;
  index.value = i;
  comments.value[i].inputShow = true;
  to.value = name;
  toId.value = id;
};

const _inputShow = (i) => {
  return comments.value[i].inputShow;
};

const sendComment = async() => {
  if (!replyComment.value) {
    proxy.Message.error("评论内容不能为空");
  } else {

    let result = await proxy.Request({
       url:api.saveRatingInfo,
       params:{
        comment: replyComment.value,
        activityId:activityId.value,
        rating:rating4User.value,
    }
    })
    if(!result){
      return;
    }
    proxy.Message.success("评论成功");

    replyComment.value = '';
    document.getElementById('replyInput').innerHTML = '';
    rating4User.value="";
    initCommentData();
  }
};

const sendCommentReply = (i, j) => {
  if (!replyComment.value) {
    alert('评论不能为空');
  } else {
    const a = {
      from: myName.value,
      to: to.value,
      fromHeadImg: myHeader.value,
      comment: replyComment.value,
      time: dateStr(new Date().getTime()),
      commentNum: 0,
      like: 0
    };
    comments.value[i].reply.push(a);
    replyComment.value = '';
    document.getElementsByClassName("reply-comment-input")[i].innerHTML = "";
  }
};

const onDivInput = (e) => {
  replyComment.value = e.target.innerHTML;
};

const dateStr = (date) => {
  const time = new Date().getTime() - date;
  if (time < 60 * 10 * 1000) {
    return '刚刚';
  } else if (time < 60 * 60 * 1000 && time >= 60 * 10 * 1000) {
    const s = Math.floor(time / 60 / 1000);
    return `${s}分钟前`;
  } else if (time < 60 * 60 * 24 * 1000 && time >= 60 * 60 * 1000) {
    const s = Math.floor(time / 60 / 60 / 1000);
    return `${s}小时前`;
  } else if (time < 60 * 60 * 24 * 30 * 1000 && time >= 60 * 60 * 24 * 1000) {
    const s = Math.floor(time / 60 / 60 / 24 / 1000);
    return `${s}天前`;
  } else {
    const d = new Date(date);
    return `${d.getFullYear()}/${d.getMonth() + 1}/${d.getDate()}`;
  }
};

const tableInfoRef = ref();
const tableData=ref({
    list:[],
});

const tableOptions = ref({
    extHeight: 400,
  });

  const columns = [

    {
      label: "志愿者编号",
      prop: "userId",
    },
    {
      label: "姓名",
      prop: "name",
    },

    {
      label: "活动名称",
      prop: "activityName",
    },
    {
      label: "加入时间",
      prop: "submitTime",
      with:200,
    }
  ];




const initCommentData=async ()=>{
    let params = {
        pageNo: tableData.value.pageNo,
        pageSize: tableData.value.pageSize,
        activityId:activityId.value,
    };
    let result = await proxy.Request({
       url:api.getRatingInfo,
       params:params
    })
    if(!result){
      return;
    }
    commentInfoList.value=result.data.list;
    Object.assign(tableData.value,result.data);
}
// 分页

const background = ref(false)
const disabled = ref(false)

const handleSizeChange = (number) => {
    tableData.value.pageSize=number;
    initCommentData();
}
const handleCurrentChange = (number) => {
    tableData.value.pageNo=number;
    initCommentData();
}





const loadJoinMemberList=async ()=>{
  let params = {
        pageNo: tableData.value.pageNo,
        pageSize: tableData.value.pageSize,
        activityId:activityId.value,
    };
    let result = await proxy.Request({
      url:api.loadJoinMemberList,
      params:params
    })
    if(!result){
      return;
    }
    tableData.value.list =result.data.list;
    }







</script>

<style lang="scss" scoped>

nav{
        padding: 10px;
        font-size: 20px;
        font-weight: bolder;
        span{
            margin-left: 10px;
            font-size:16px;
            color: rgb(29, 32, 136);
            cursor: pointer;
        }
    }

.nodata{
    display: flex;
    justify-content: center;
    padding: 10px 10px 10px 10px;
    color: rgb(29, 32, 136);
    font-weight: bolder;
}


</style>
<style lang="stylus" scoped>
    .my-reply
        padding 10px
        background-color #fafbfc
        .header-img
            display inline-block
            vertical-align top
        .reply-info
            display inline-block
            margin-left 5px
            width 90%
            @media screen and (max-width:1200px) {
                width 80%
            }
            .reply-input
                min-height 20px
                line-height 22px
                padding 10px 10px
                color #ccc
                background-color #fff
                border-radius 5px
                &:empty:before
                    content attr(placeholder)
                &:focus:before
                    content none
                &:focus
                    padding 8px 8px
                    border 2px solid blue
                    box-shadow none
                    outline none
        .reply-btn-box
            height 25px
            margin 10px 0
            .reply-btn
                position relative
                float right
                margin-right 15px
    .my-comment-reply
        margin-left 50px
        .reply-input
            width flex
    .author-title:not(:last-child)
        border-bottom: 1px solid rgba(178,186,194,.3)
    .author-title
        padding 10px
        .header-img
            display inline-block
            vertical-align top
        .author-info
            display inline-block
            margin-left 5px
            width 60%
            height 40px
            line-height 20px
            >span
                display block
                cursor pointer
                overflow hidden
                white-space nowrap
                text-overflow ellipsis
            .author-name
                color #000
                font-size 18px
                font-weight bold
            .author-time
                font-size 14px
        .icon-btn
            width 30%
            padding 0 !important
            float right
            @media screen and (max-width : 1200px){
                width 20%
                padding 7px
            }
            >span
                cursor pointer
            .iconfont
                margin 0 5px
        .talk-box
            margin 0 50px
            >p
            margin 0
            .reply
                font-size 16px
                color #000
        .reply-box
            margin 10px 0 0 50px
            background-color #efefef
</style>